package com.example.triprec.ui.dialog;

import android.app.DatePickerDialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.example.triprec.R;
import com.example.triprec.common.Result;
import com.example.triprec.dao.TripDao;
import com.example.triprec.entity.Trip;

import java.util.Calendar;

/**
 * 添加/编辑行程对话框
 */
public class EditTripDialog {

    private Context context;
    private Long userId;
    private Long scenicId;
    private String scenicName;
    private Trip mTrip; // 当前编辑的行程对象
    private boolean isEditMode; // 编辑模式标识

    private AlertDialog dialog;
    private EditText etTripName;
    private TextView tvStartDate;
    private TextView tvEndDate;

    private OnTripEditListener mListener;

    public interface OnTripEditListener {
        void onTripEditSuccess(Trip trip);
    }

    /**
     * 添加行程构造方法
     */
    public EditTripDialog(Context context, Long userId, Long scenicId, String scenicName) {
        this.context = context;
        this.userId = userId;
        this.scenicId = scenicId;
        this.scenicName = scenicName;
        this.isEditMode = false;
    }

    /**
     * 编辑行程构造方法
     */
    public EditTripDialog(Context context, Trip trip) {
        this.context = context;
        this.mTrip = trip;
        this.userId = trip.getUserId();
        this.scenicId = trip.getScenicId();
        if (trip.getScenic() != null) {
            this.scenicName = trip.getScenic().getName();
        }
        this.isEditMode = true;
    }

    public void setOnTripEditListener(OnTripEditListener listener) {
        this.mListener = listener;
    }

    /**
     * 显示对话框
     */
    public void show() {
        if (userId == null || scenicId == null) {
            Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建对话框视图
        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_edit_trip, null);
        etTripName = dialogView.findViewById(R.id.et_trip_name);
        tvStartDate = dialogView.findViewById(R.id.tv_start_date);
        tvEndDate = dialogView.findViewById(R.id.tv_end_date);

        // 设置行程名称和日期（根据模式）
        if (isEditMode && mTrip != null) {
            etTripName.setText(mTrip.getTripName());
            tvStartDate.setText(mTrip.getStartDate());
            if (mTrip.getEndDate() != null) {
                tvEndDate.setText(mTrip.getEndDate());
            }
        } else {
            // 设置默认行程名称
            etTripName.setText("游览" + scenicName);
        }

        // 设置日期选择器点击事件
        tvStartDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(tvStartDate, true);
            }
        });

        tvEndDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(tvEndDate, false);
            }
        });

        // 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(isEditMode ? "编辑行程" : "添加行程")
                .setView(dialogView)
                .setPositiveButton("确定", null)
                .setNegativeButton("取消", null);

        dialog = builder.create();
        dialog.show();

        // 设置确定按钮点击事件（防止点击后自动关闭对话框）
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitTrip();
            }
        });
    }

    /**
     * 显示日期选择器对话框
     *
     * @param textView    显示选中日期的文本视图
     * @param isStartDate 是否是开始日期（用于设置最小日期限制）
     */
    private void showDatePickerDialog(final TextView textView, boolean isStartDate) {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(context,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String date = year + "-" + (month + 1) + "-" + dayOfMonth;
                        textView.setText(date);

                        // 如果设置了开始日期，并且结束日期为空或小于开始日期，则自动设置结束日期
                        if (isStartDate && !TextUtils.isEmpty(tvStartDate.getText())) {
                            String endDateText = tvEndDate.getText().toString();
                            if (TextUtils.isEmpty(endDateText) || "选择出行结束日期".equals(endDateText)) {
                                tvEndDate.setText(date);
                            }
                        }
                    }
                }, year, month, day);

        // 设置最小日期
        if (isStartDate) {
            // 开始日期不能早于今天，但在编辑模式下可以选择过去的日期
            if (!isEditMode) {
                datePickerDialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
            }
        } else {
            // 结束日期不能早于开始日期
            String startDateText = tvStartDate.getText().toString();
            if (!TextUtils.isEmpty(startDateText) && !"选择出行开始日期".equals(startDateText)) {
                try {
                    String[] parts = startDateText.split("-");
                    if (parts.length == 3) {
                        Calendar startCal = Calendar.getInstance();
                        startCal.set(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]) - 1, Integer.parseInt(parts[2]));
                        datePickerDialog.getDatePicker().setMinDate(startCal.getTimeInMillis());
                    }
                } catch (Exception e) {
                    if (!isEditMode) {
                        datePickerDialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
                    }
                }
            } else {
                if (!isEditMode) {
                    datePickerDialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
                }
            }
        }

        datePickerDialog.show();
    }

    /**
     * 提交行程
     */
    private void submitTrip() {
        String tripName = etTripName.getText().toString().trim();
        String startDate = tvStartDate.getText().toString().trim();
        String endDate = tvEndDate.getText().toString().trim();

        // 验证输入
        if (TextUtils.isEmpty(tripName)) {
            Toast.makeText(context, "行程名称不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(startDate) || "选择出行开始日期".equals(startDate)) {
            Toast.makeText(context, "请选择出行开始日期", Toast.LENGTH_SHORT).show();
            return;
        }

        Result<?> result;
        Trip trip;

        if (isEditMode) {
            // 编辑行程模式
            trip = mTrip;
            trip.setTripName(tripName);
            trip.setStartDate(startDate);

            if (!TextUtils.isEmpty(endDate) && !"选择出行结束日期".equals(endDate)) {
                trip.setEndDate(endDate);
            } else {
                trip.setEndDate(null); // 清空结束日期
            }

            result = TripDao.updateTrip(trip);
        } else {
            // 添加行程模式
            trip = new Trip();
            trip.setUserId(userId);
            trip.setScenicId(scenicId);
            trip.setTripName(tripName);
            trip.setStartDate(startDate);

            if (!TextUtils.isEmpty(endDate) && !"选择出行结束日期".equals(endDate)) {
                trip.setEndDate(endDate);
            }

            result = TripDao.addTrip(trip);
        }

        if (result.isSuccess()) {
            String successMsg = isEditMode
                    ? "行程编辑成功"
                    : "已将 " + scenicName + " 加入行程";
            Toast.makeText(context, successMsg, Toast.LENGTH_SHORT).show();

            // 回调通知操作成功
            if (mListener != null) {
                mListener.onTripEditSuccess(trip);
            }
            
            dialog.dismiss();
        } else {
            Toast.makeText(context, result.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
} 